package com.itbour.common.util;


import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dm.model.v20151123.SingleSendSmsRequest;
import com.aliyuncs.dm.model.v20151123.SingleSendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.itbour.common.log.DebugLogger;
import com.itbour.def.SystemConf;


public class AliSmsUtil {
	
	private static final String ACCESS_KEY_ID = SystemConf.getOssAccessKeyId();
    private static final String ACCESS_KEY_SECRET = SystemConf.getOssAccessKeySecret();

    // mobile: 手机号（多个时,逗号分隔）
	public String sendVerCode(String mobile) {
		String verCode = AliSmsUtil.randomNumStr(6);
		try {
			IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", ACCESS_KEY_ID, ACCESS_KEY_SECRET);
			IAcsClient client = new DefaultAcsClient(profile);
			
			SingleSendSmsRequest req = new SingleSendSmsRequest();
			req.setAcceptFormat(FormatType.JSON);
            req.setSignName("示界港");
            req.setTemplateCode("SMS_12921147");
            req.setRecNum(mobile);
            req.setParamString("{\"code\":\""+verCode+"\"}");
            
            SingleSendSmsResponse httpResponse = client.getAcsResponse(req);
            if(httpResponse!=null) {
            	DebugLogger.log(httpResponse.toString());
            }
            
		} catch (ServerException e) {
            //e.printStackTrace();
            throw new RuntimeException("Aliyun ServerException: "+e.getErrMsg(), e);
            //return null;
        } catch (ClientException e) {
            //e.printStackTrace();
            throw new RuntimeException("Aliyun ClientException: "+e.getErrMsg(), e);
            //return null;
        }
		
		return verCode;
	}
	
	public static String randomNumStr(int len){
        String ret = "";
        for (int i = 0; i < len; i++) {
            ret += String.valueOf((int)(Math.random() * 10));
        }
        return ret;
    }
}

